<template>
  <div class="page">
    <!-- 筛选：类型、状态、有效期 -->
    <el-form :inline="true" :model="query" class="mb-12">
      <el-form-item label="类型">
        <el-select v-model="query.type" placeholder="请选择" clearable>
          <el-option label="满减券" value="fullcut" />
          <el-option label="折扣券" value="discount" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.status" placeholder="请选择" clearable>
          <el-option label="未开始" value="not_started" />
          <el-option label="生效中" value="active" />
          <el-option label="已过期" value="expired" />
        </el-select>
      </el-form-item>
      <el-form-item label="有效期">
        <el-date-picker v-model="query.range" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作：新增、批量停用 -->
    <div class="mb-12">
      <el-button type="primary" @click="openEdit()">新增优惠券</el-button>
      <el-button type="warning" :disabled="!selection.length" @click="onBatchDisable">批量停用</el-button>
    </div>

    <!-- 列表：字段展示 -->
    <el-table :data="list" @selection-change="selection = $event" border>
      <el-table-column type="selection" width="48" />
      <el-table-column prop="name" label="名称" min-width="160" />
      <el-table-column prop="typeText" label="类型" width="120" />
      <el-table-column prop="valueText" label="面值/折扣率" width="140" />
      <el-table-column prop="thresholdText" label="使用门槛" width="140" />
      <el-table-column prop="periodText" label="有效期" min-width="200" />
      <el-table-column prop="total" label="总发行量" width="120" />
      <el-table-column prop="used" label="已使用" width="120" />
      <el-table-column prop="remain" label="剩余" width="120" />
      <el-table-column prop="statusText" label="状态" width="120" />
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)">编辑</el-button>
          <el-button size="small" type="warning" @click="onDisable(row)">停用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="mt-12 flex-end">
      <el-pagination background layout="prev, pager, next, total" :total="total" :page-size="pageSize" :current-page="page" @current-change="(p)=>{page=p; fetchList()}" />
    </div>

    <!-- 编辑弹窗：校验有效期逻辑（开始时间≤结束时间） -->
    <el-dialog v-model="visible" :title="form.id ? '编辑优惠券' : '新增优惠券'" width="640px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="110px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="fullcut">满减券</el-radio>
            <el-radio label="discount">折扣券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="面值/折扣率" prop="value">
          <el-input-number v-model="form.value" :min="0" :max="100" :step="1" />
        </el-form-item>
        <el-form-item label="使用门槛" prop="threshold">
          <el-input-number v-model="form.threshold" :min="0" :step="10" />
        </el-form-item>
        <el-form-item label="有效期" prop="period">
          <el-date-picker v-model="form.period" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
        <el-form-item label="总发行量" prop="total">
          <el-input-number v-model="form.total" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="visible=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="onSubmit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 优惠券管理页面：增删改查、批量停用与有效期校验
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

const query = reactive({ type: '', status: '', range: [] })
const list = ref([])
const selection = ref([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

const visible = ref(false)
const saving = ref(false)
const formRef = ref()
const form = reactive({ id: null, name: '', type: 'fullcut', value: 10, threshold: 200, period: [], total: 100 })

// 有效期校验：开始时间≤结束时间
const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  value: [{ required: true, message: '请输入面值/折扣率', trigger: 'change' }],
  period: [{ validator:(_,v,cb)=> cb(!v || v.length!==2 || dayjs(v[0]).isAfter(v[1]) ? new Error('开始时间需小于等于结束时间') : undefined), trigger: 'change' }]
}

function fetchList(){
  const items = Array.from({ length: pageSize.value }, (_, i) => {
    const type = i % 2 === 0 ? 'fullcut' : 'discount'
    const status = ['not_started','active','expired'][i % 3]
    return {
      id: i+1,
      name: `优惠券${i+1}`,
      typeText: type === 'fullcut' ? '满减券' : '折扣券',
      valueText: type === 'fullcut' ? `${10+i}元` : `${90-i}%`,
      thresholdText: `满${200+i*10}可用`,
      periodText: `${dayjs().format('YYYY-MM-DD')} 至 ${dayjs().add(7,'day').format('YYYY-MM-DD')}`,
      total: 1000,
      used: i*5,
      remain: 1000 - i*5,
      status,
      statusText: status === 'not_started' ? '未开始' : status === 'active' ? '生效中' : '已过期'
    }
  })
  list.value = items
  total.value = 60
}

function onSearch(){ page.value = 1; fetchList() }
function onReset(){ query.type=''; query.status=''; query.range=[]; onSearch() }

function openEdit(row){
  if(row){ Object.assign(form, { id: row.id, name: row.name }) }
  else { Object.assign(form, { id: null, name: '', type: 'fullcut', value: 10, threshold: 200, period: [], total: 100 }) }
  visible.value = true
}

function onSubmit(){
  formRef.value.validate((ok)=>{
    if(!ok) return
    saving.value = true
    setTimeout(()=>{ saving.value=false; visible.value=false; ElMessage.success('提交成功（示例）'); fetchList() }, 600)
  })
}

function onDisable(row){
  ElMessageBox.confirm('确认停用该优惠券吗？', '提示', { type: 'warning' }).then(()=>{
    ElMessage.success('已停用（示例）')
    fetchList()
  })
}

function onBatchDisable(){
  ElMessageBox.confirm(`确认批量停用选中的 ${selection.value.length} 个优惠券吗？`, '提示', { type: 'warning' }).then(()=>{
    ElMessage.success('批量停用成功（示例）')
    fetchList()
  })
}

onMounted(fetchList)
</script>

<style scoped>
.page { background: #fff; padding: 16px; border: 1px solid #ebeef5; }
.mb-12 { margin-bottom: 12px; }
.mt-12 { margin-top: 12px; }
.flex-end { display: flex; justify-content: flex-end; }
</style>